package com.m20studio.mop.activity;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.m20studio.mop.R;
import com.m20studio.mop.http.HttpConnectionUtil;
import com.m20studio.mop.http.HttpConnectionUtil.HttpConnectionCallback;
import com.m20studio.mop.http.HttpConnectionUtil.HttpMethod;
import com.m20studio.mop.xml.XMLFeed;
import com.m20studio.mop.xml.XMLHandler;

public class ViewTz extends Activity{
	
	private String url;
	private String xurl;
	private List<XMLFeed> xmllists;

	private int page = 0;
	private LinearLayout loading;
	private AnimationDrawable loadingAnim;
	private TextView pageInfo;
	private XMLFeed feed;
	private String contentLz;
	private int screenWidth;
	private LinearLayout bottomBarButton1,bottomBarButton2,bottomBarButton3,bottomBarButton4,bottomBarButton5;
	private int pageCount=9999;
	private WebSettings webSettings;
	private ProgressDialog Dialog;
	private int moreNum = 1;
	private LinearLayout topBarMore;
	private LinearLayout viewTzMoreB1,viewTzMoreB2;
	private TextView topTitle;
	private boolean moreDisplay;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.viewtz); 
        
        //获取屏幕宽度以便使图片适应屏幕分辨率
      	WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);  
      	screenWidth = wm.getDefaultDisplay().getWidth();
      	if(screenWidth>480){
      		screenWidth = 480;
      	}
      		
        //loading动画
        loading = (LinearLayout) findViewById(R.id.top_bar_reload);
        loading.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	htmlHandler(url,page);
            } 
		});
        
        //loading提示
        Dialog = new ProgressDialog(this);
		Dialog.setMessage("数据读取中，过程可能会比较长，请耐心等待...");
        
        //获取Activity传值
        feed = (XMLFeed) getIntent().getSerializableExtra("url");
        url = feed.getURL();
        xurl = url;
        //url="http://dzh.mop.com/whbm/20120310/0/O3lglOI2909d66F3.shtml";
        
        
        //当前页面信息
        pageInfo = (TextView) findViewById(R.id.top_pageinfo);
        pageInfo.setText("第"+(page+1)+"页");
        
      //页面title
        topTitle = (TextView) findViewById(R.id.top_title);
        topTitle.setText("帖子正文");
        
        //more控制按钮
      	topBarMore = (LinearLayout) findViewById(R.id.top_bar_more);
      	topBarMore.setOnClickListener(new View.OnClickListener() {            
			public void onClick(View v){
            	if(!moreDisplay){
            		showMore();
      				moreDisplay = true;				
      			}else{
      				moreWindow.dismiss();
      				moreDisplay = false;
      			}
            } 
    	});
        
        //bottomBarButton1_返回
		bottomBarButton1 = (LinearLayout)findViewById(R.id.viewtz_bottom_bar_button_back);
		bottomBarButton1.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	ViewTz.this.setResult(RESULT_OK);
            	ViewTz.this.finish();
              } 
		});
		
		//bottomBarButton2_首页
		bottomBarButton2 = (LinearLayout)findViewById(R.id.viewtz_bottom_bar_button_first);						
		bottomBarButton2.setOnClickListener(new View.OnClickListener() { 
			public void onClick(View v){ 
				if(page <= 0){
            		showToast("当前已经是第一页了");
            	}else{
            		page = 0;
                	htmlHandler(url,page);
                	pageInfo.setText("第"+(page+1)+"页");
            	}
				
		    } 
		});		
		
		//bottomBarButton3_上一页
		bottomBarButton3 = (LinearLayout)findViewById(R.id.viewtz_bottom_bar_button_previous);						
		bottomBarButton3.setOnClickListener(new View.OnClickListener() { 
			public void onClick(View v){ 
				if(page <= 0){
            		showToast("当前已经是第一页了");
            	}else{
            		page -- ;
            		htmlHandler(url,page);
            		pageInfo.setText("第"+(page+1)+"页");
            	}
		    } 
		});
		
		//bottomBarButton4_下一页
		bottomBarButton4 = (LinearLayout)findViewById(R.id.viewtz_bottom_bar_button_next);						
		bottomBarButton4.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){ 
            	if (page >= pageCount){
					showToast("当前已经是最后一页了");
				}else{
					page ++;
		            htmlHandler(url, page);
		            pageInfo.setText("第"+(page+1)+"页");
				}
	            
            } 
		});

		//bottomBarButton5_尾页
		bottomBarButton5 = (LinearLayout)findViewById(R.id.viewtz_bottom_bar_button_last);						
		bottomBarButton5.setOnClickListener(new View.OnClickListener() { 
			public void onClick(View v){
				if (page >= pageCount){
					showToast("当前已经是最后一页了");
				}else{
					page = pageCount;
				    htmlHandler(url, page);
				    pageInfo.setText("第"+(page+1)+"页");
				}
		    } 
		});
        
		//加载网络数据
	    htmlHandler(url,0);	    

    }
    
    
    //定义more
  	private PopupWindow moreWindow; 		
  	private LayoutInflater inflaterMore; 
  	private View layoutMore;
  	private LinearLayout viewTzMore;
  	private FrameLayout viewTzMoreBg;
  	//显示more
  	public void showMore(){	
  		inflaterMore = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
  		layoutMore = inflaterMore.inflate(R.layout.viewtz_more, null);
  		moreWindow = new PopupWindow(layoutMore,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); 
  		moreWindow.setAnimationStyle(R.style.MoreAnimation); 
  		moreWindow.showAtLocation(this.findViewById(R.id.viewtz), Gravity.BOTTOM, 0, 0);
  		//more_bg
  		viewTzMoreBg = (FrameLayout)layoutMore.findViewById(R.id.viewtz_more_bg);
  		switch(moreNum){
  		case 1:
  			viewTzMoreBg.setBackgroundResource(R.drawable.viewtz_more_1);
  			break;
  		case 2:
  			viewTzMoreBg.setBackgroundResource(R.drawable.viewtz_more_2);
  			break;
  		}
  		//more_close
  		viewTzMore = (LinearLayout)layoutMore.findViewById(R.id.viewtz_more);						
  		viewTzMore.setOnClickListener(new View.OnClickListener() { 
              public void onClick(View v){ 
              		moreWindow.dismiss();
              		moreDisplay = false;
                } 
  		});
  		//viewTzMoreB1
  		viewTzMoreB1 = (LinearLayout)layoutMore.findViewById(R.id.viewtz_more_b1);						
  		viewTzMoreB1.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	viewTzMoreBg.setBackgroundResource(R.drawable.viewtz_more_1);
            	moreWindow.dismiss();
            	url=xurl;
            	htmlHandler(url,0);
            	moreNum = 1;
            	page = 0;
            	pageInfo.setText("第"+page+"页");
              } 
		});
		//viewTzMoreB2
  		viewTzMoreB2 = (LinearLayout)layoutMore.findViewById(R.id.viewtz_more_b2);						
  		viewTzMoreB2.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v){
            	viewTzMoreBg.setBackgroundResource(R.drawable.viewtz_more_2);
            	moreWindow.dismiss();
            	if (url.indexOf("?only")<0){
            		url=url+"?only=1";
            	}
            	htmlHandler(url,0);
            	moreNum = 2;
            	page = 0;
            	pageInfo.setText("第"+page+"页");
              } 
		});  		
  	}
    
    //发送url和页数
    public void htmlHandler(final String url, final int page){

    	Dialog.show();
    	loading.setBackgroundResource(R.anim.loading);
        loadingAnim = (AnimationDrawable) loading.getBackground();
        loadingAnim.setOneShot(false);
    	loadingAnim.start();
    	final Handler handler = new Handler(){ 		
			@Override
			public void handleMessage(Message msg){
				if (msg.what == 1){
					loading.setBackgroundResource(R.drawable.top_bar_reload);
					WebView viewTzContent=(WebView) findViewById(R.id.viewtz_content);
			        viewTzContent.getSettings().setJavaScriptEnabled(false);
			        viewTzContent.getSettings().setSupportZoom(false);
			        viewTzContent.setWebViewClient(new webViewClient());

			        //webview宽度自适应
			        webSettings= viewTzContent.getSettings();
			        webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
			        //去除滚动条背景
			        viewTzContent.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
			        viewTzContent.setBackgroundColor(Color.TRANSPARENT);
					viewTzContent.loadDataWithBaseURL("http://wap.baidu.com", contentLz, "text/html", "utf-8", null);
					loadingAnim.stop();
					Dialog.cancel();
				}
			}
		};
    	new Thread(){
    		public void run(){
    			Looper.prepare();
    			try{
					Thread.sleep(100);

				}catch (InterruptedException e){
					e.printStackTrace();
				}
    			try{

                	
    				htmlConnect(url, page);  				
					setInListView();
					
    			}catch(Exception e){
    				
    			}
    			Message m = new Message();
				m.what = 1;
				handler.sendMessage(m);
				Looper.loop();
    		}
    	}.start();
    }
    
    //从网络取得数据填充ListView
    private void setInListView(){        
    	if (xmllists.isEmpty()){
    		showToast("数据请求异常，请重试或放弃！");
		}else{

			for (XMLFeed feed : xmllists){
				contentLz = feed.getContent();
				pageCount = feed.getPageCount();
				//Log.e("m20",pageCount+"总页数");
			}
			
		}
		
    	
	}
    
    //连接网络获取数据
    private void htmlConnect(String url, final int page) throws Exception{
    	List<String> list = Arrays.asList(this.url.split("/"));
		String str = page+"";
		list.set(5,str);
		url = list.toString().replaceAll(",", "/").replaceAll(" ", "").replace("[", "").replace("]", "");    		
    		
		Map<String, String> map = new HashMap<String, String>();
		//map.put("page", String.valueOf(page));
	
		HttpConnectionUtil conn = new HttpConnectionUtil();
		conn.syncConnect(url, map, HttpMethod.GET, new HttpConnectionCallback(){
				
			public void execute(String response){
				XMLHandler handler = new XMLHandler();
				handler.handlerViewTz(response,screenWidth,page);
				xmllists = handler.getListFeed();
			}
		});
	} 

    //弹出提示栏    
    private void showToast(String str){
		Toast.makeText(this, str, 1).show();
	}
    
    //重写shouldOverrideUrlLoading方法，使点击链接后不使用其他的浏览器打开 
    public class webViewClient extends WebViewClient{ 
     
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
         //view.loadUrl(url); 
         //如果不需要其他对点击链接事件的处理返回true，否则返回false 
         return true; 
     } 
         
    }
}